<template>
  <div class="document-container">
    <!-- 顶部工具栏 -->
    <div class="document-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="createDocument">
          <el-icon><Plus /></el-icon>
          新建文档
        </el-button>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索文档..."
          style="width: 300px; margin-left: 16px;"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>
      <div class="toolbar-right">
        <el-button @click="showTemplates = true">
          <el-icon><Document /></el-icon>
          模板
        </el-button>
      </div>
    </div>

    <!-- 文档列表 -->
    <div class="document-list">
      <div 
        v-for="document in documents"
        :key="document.id"
        class="document-card"
        @click="openDocument(document)"
      >
        <div class="document-icon">
          <el-icon size="32" color="#409eff"><Document /></el-icon>
        </div>
        <div class="document-info">
          <h3 class="document-title">{{ document.title }}</h3>
          <p class="document-summary">{{ document.summary }}</p>
          <div class="document-meta">
            <div class="meta-left">
              <el-avatar :size="20" :src="document.creatorAvatar" />
              <span class="creator">{{ document.creatorName }}</span>
              <span class="version">v{{ document.version }}</span>
            </div>
            <div class="meta-right">
              <span class="update-time">{{ formatTime(document.updateTime) }}</span>
              <el-tag 
                :type="getStatusType(document.status)"
                size="small"
              >
                {{ getStatusText(document.status) }}
              </el-tag>
            </div>
          </div>
          <div class="document-actions">
            <el-button size="small" type="text" @click.stop="shareDocument(document)">
              <el-icon><Share /></el-icon>
              分享
            </el-button>
            <el-button size="small" type="text" @click.stop="viewVersions(document)">
              <el-icon><Clock /></el-icon>
              版本
            </el-button>
            <el-dropdown @command="(command) => handleCommand(command, document)" @click.stop>
              <el-button size="small" type="text">
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit">编辑</el-dropdown-item>
                  <el-dropdown-item command="duplicate">复制</el-dropdown-item>
                  <el-dropdown-item command="export">导出</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more">
      <el-button @click="loadMore" :loading="loading">加载更多</el-button>
    </div>

    <!-- 文档模板对话框 -->
    <el-dialog v-model="showTemplates" title="文档模板" width="800px">
      <div class="template-grid">
        <div 
          v-for="template in documentTemplates"
          :key="template.id"
          class="template-card"
          @click="useTemplate(template)"
        >
          <div class="template-preview">
            <el-icon size="48" color="#409eff"><Document /></el-icon>
          </div>
          <div class="template-info">
            <h4>{{ template.title }}</h4>
            <p>{{ template.description }}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  getDocumentList, 
  searchDocuments,
  deleteDocument,
  getDocumentTemplates,
  createDocumentFromTemplate
} from '@/api/document'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const documents = ref([])
const documentTemplates = ref([])
const showTemplates = ref(false)
const loading = ref(false)
const hasMore = ref(true)

// 分页参数
const pagination = reactive({
  page: 1,
  size: 20
})

// 获取文档列表
const getDocuments = async (reset = false) => {
  if (loading.value) return
  
  loading.value = true
  try {
    const params = {
      page: reset ? 1 : pagination.page,
      size: pagination.size
    }
    
    const response = await getDocumentList(params)
    if (response.code === 200) {
      const newDocuments = response.data.records || []
      if (reset) {
        documents.value = newDocuments
        pagination.page = 1
      } else {
        documents.value.push(...newDocuments)
      }
      
      hasMore.value = newDocuments.length === pagination.size
      if (!reset) {
        pagination.page++
      }
    }
  } catch (error) {
    console.error('获取文档列表失败:', error)
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

// 获取文档模板
const loadDocumentTemplates = async () => {
  try {
    const response = await getDocumentTemplates()
    if (response.code === 200) {
      documentTemplates.value = response.data
    }
  } catch (error) {
    console.error('获取文档模板失败:', error)
  }
}

// 搜索文档
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    getDocuments(true)
    return
  }
  
  loading.value = true
  try {
    const response = await searchDocuments(searchKeyword.value, {
      page: 1,
      size: pagination.size
    })
    if (response.code === 200) {
      documents.value = response.data.records || []
      hasMore.value = false
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  getDocuments()
}

// 创建文档
const createDocument = () => {
  router.push('/document/create')
}

// 打开文档
const openDocument = (document) => {
  router.push(`/document/${document.id}`)
}

// 使用模板
const useTemplate = async (template) => {
  try {
    const response = await createDocumentFromTemplate(template.id, {
      title: `基于${template.title}的新文档`
    })
    if (response.code === 200) {
      showTemplates.value = false
      router.push(`/document/${response.data.id}/edit`)
    }
  } catch (error) {
    console.error('使用模板失败:', error)
    ElMessage.error('使用模板失败')
  }
}

// 分享文档
const shareDocument = (document) => {
  ElMessage.info('分享功能开发中...')
}

// 查看版本
const viewVersions = (document) => {
  router.push(`/document/${document.id}/versions`)
}

// 处理命令
const handleCommand = (command, document) => {
  switch (command) {
    case 'edit':
      router.push(`/document/${document.id}/edit`)
      break
    case 'duplicate':
      handleDuplicate(document)
      break
    case 'export':
      handleExport(document)
      break
    case 'delete':
      handleDelete(document)
      break
  }
}

// 复制文档
const handleDuplicate = (document) => {
  ElMessage.info('复制功能开发中...')
}

// 导出文档
const handleExport = (document) => {
  ElMessage.info('导出功能开发中...')
}

// 删除文档
const handleDelete = (document) => {
  ElMessageBox.confirm(`确认要删除文档"${document.title}"吗？`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDocument(document.id)
      ElMessage.success('删除成功')
      getDocuments(true)
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 工具函数
const getStatusType = (status) => {
  const typeMap = {
    'PUBLISHED': 'success',
    'DRAFT': 'warning',
    'ARCHIVED': 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'PUBLISHED': '已发布',
    'DRAFT': '草稿',
    'ARCHIVED': '归档'
  }
  return textMap[status] || status
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleDateString()
}

// 页面加载
onMounted(() => {
  getDocuments(true)
  loadDocumentTemplates()
})
</script>

<style lang="scss" scoped>
.document-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.document-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
  
  .toolbar-left {
    display: flex;
    align-items: center;
  }
}

.document-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 16px;
}

.document-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  display: flex;
  gap: 12px;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  }
  
  .document-icon {
    flex-shrink: 0;
  }
  
  .document-info {
    flex: 1;
    
    .document-title {
      margin: 0 0 8px 0;
      font-size: 16px;
      font-weight: 600;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .document-summary {
      margin: 0 0 12px 0;
      color: #666;
      font-size: 14px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    
    .document-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      font-size: 12px;
      color: #666;
      
      .meta-left {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .version {
          background: #f0f0f0;
          padding: 2px 6px;
          border-radius: 4px;
        }
      }
      
      .meta-right {
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }
    
    .document-actions {
      display: flex;
      gap: 8px;
    }
  }
}

.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.template-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    border-color: #409eff;
    background: #f8f9fa;
  }
  
  .template-preview {
    margin-bottom: 12px;
  }
  
  .template-info {
    h4 {
      margin: 0 0 8px 0;
      font-size: 14px;
    }
    
    p {
      margin: 0;
      font-size: 12px;
      color: #666;
    }
  }
}

.load-more {
  text-align: center;
  margin: 20px 0;
}

@media (max-width: 768px) {
  .document-container {
    padding: 12px;
  }
  
  .document-list {
    grid-template-columns: 1fr;
  }
  
  .template-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style>
